package com.cxs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxs.model.ProductInfo;
import com.cxs.service.ProductInfoService;
import com.cxs.mapper.ProductInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
* @author DELL
* @description 针对表【t_product_info(商品表)】的数据库操作Service实现
* @createDate 2023-01-07 16:57:34
*/
@Service
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper, ProductInfo>
    implements ProductInfoService{

    @Autowired
    private ProductInfoMapper productInfoMapper;

    // ReentrantLock lock = new ReentrantLock(true);

//    @Override
//    public Integer saveProduct() {
//        lock.lock();
//        try {
//            // 获取库中最大的一个编号
//            LambdaQueryWrapper<ProductInfo> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.orderByDesc(ProductInfo::getProductOrder).select(ProductInfo::getProductId, ProductInfo::getProductOrder).last(" limit 1");
//            ProductInfo maxProductInfo = productInfoMapper.selectOne(queryWrapper);
//            // 存数据，在此处自己造数据，实际应该是接口参数带过来
//            ProductInfo productInfo = new ProductInfo();
//            productInfo.setProductName(UUID.randomUUID().toString());
//            productInfo.setProductOrder(ObjectUtils.isEmpty(maxProductInfo) ? 1 : maxProductInfo.getProductOrder() + 1);
//            productInfo.setCreateTime(LocalDateTime.now());
//            return productInfoMapper.insert(productInfo);
//        } finally {
//            lock.unlock();
//        }
//    }

    @Override
    public synchronized Integer saveProduct() {
        // 获取库中最大的一个编号
        LambdaQueryWrapper<ProductInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ProductInfo::getProductOrder).select(ProductInfo::getProductId, ProductInfo::getProductOrder).last(" limit 1");
        ProductInfo maxProductInfo = productInfoMapper.selectOne(queryWrapper);
        // 存数据，在此处自己造数据，实际应该是接口参数带过来
        ProductInfo productInfo = new ProductInfo();
        productInfo.setProductName(UUID.randomUUID().toString());
        productInfo.setProductOrder(ObjectUtils.isEmpty(maxProductInfo) ? 1 : maxProductInfo.getProductOrder() + 1);
        productInfo.setCreateTime(LocalDateTime.now());
        return productInfoMapper.insert(productInfo);
    }
}




